package com.ey.generator.util;

import com.ey.generator.config.GenConfig;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import freemarker.template.TemplateExceptionHandler;

import java.io.File;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.util.HashMap;
import java.util.Map;

/**
 * 生成工具
 * @author zhuang_ming_nan
 * @since 2019/9/27 19:12
 */
public class GenUtil {

    private static final GenConfig genConfig = new GenConfig();
    private static final Configuration cfg;
    private static final String path = "D:/mingnan/code/my/ey-system/ey-generator/src/main/resources/template";

    static {

        cfg = new Configuration(Configuration.VERSION_2_3_22);
        try {
            cfg.setDirectoryForTemplateLoading(new File(path));
        } catch (IOException e) {
            e.printStackTrace();
        }
        cfg.setDefaultEncoding("UTF-8");
        cfg.setTemplateExceptionHandler(TemplateExceptionHandler.RETHROW_HANDLER);
    }

    public static void gen(String className, String templateLocation, Map<String, Object> data)
            throws IOException, TemplateException {

        data.put("author", genConfig.getAuthor());
        data.put("className", className);

        Template temp = cfg.getTemplate(templateLocation);
        Writer out = new OutputStreamWriter(System.out);
        temp.process(data, out);

    }


    public static void main(String[] args) throws IOException, TemplateException {
       GenUtil.gen("health",
               "Controller.ftl",
                new HashMap<>());
    }
}
